﻿/*----------------------------------------------------------------
// Copyright (C) 2016 通通优品版权所有。
// 命名空间: TongTongMall.MallWeb.Core.Test.Configuration
// 类名：FolderAssemblyFinder
// 功能描述：N/A
// 
// 创建标识：Roc.Lee(李鹏鹏) 2017/5/3 16:13:01 TEC-ROCLEE Roc.Lee

// 修改标识：
// 修改描述：
// 
//
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Reflection;

namespace TongTongMall.MallWeb.Core.Test.Configuration
{
    public class FolderAssemblyFinder : IAssemblyFinder
    {
        public string FolderPath { get; private set; }

        public SearchOption SearchOption { get; private set; }

        private List<Assembly> _assemblies;

        private readonly object _syncLock = new object();

        public FolderAssemblyFinder(string folderPath, SearchOption searchOption = SearchOption.TopDirectoryOnly)
        {
            FolderPath = folderPath;
            SearchOption = searchOption;
        }

        public List<Assembly> GetAllAssemblies()
        {
            if (_assemblies == null)
            {
                lock (_syncLock)
                {
                    if (_assemblies == null)
                    {
                        _assemblies = GetAllAssembliesInternal();
                    }
                }
            }

            return _assemblies;
        }

        private List<Assembly> GetAllAssembliesInternal()
        {
            var assemblies = new List<Assembly>();
            var dllFiles = Directory.GetFiles(FolderPath, "*.dll", SearchOption);

            foreach (string dllFile in dllFiles)
            {
                FileInfo file = new FileInfo(dllFile);
                if (!file.Name.Contains("TongTongMall")) continue;
                assemblies.Add(Assembly.LoadFile(dllFile));
            }

            return assemblies;
        }
    }
}
